package com.hellogood.yaohuo.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hellogood.yaohuo.server.db.DBHelper;
import com.hellogood.yaohuo.shared.entity.Quyu;
import com.hellogood.yaohuo.shared.exception.DatabaseException;

public class QuyuDAO extends DBHelper {

	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<Quyu> qyList = new ArrayList<Quyu>();
		if (rs != null) {
			while (rs.next()) {
				Quyu qy = new Quyu();
				qy.setQyCode(rs.getString("QyCode"));
				qy.setQyName(rs.getString("QyName"));
				qyList.add(qy);
			}
		}
		return qyList;
	}

	public List<Quyu> getAllQy() {
		String sql = "SELECT * FROM qy";
		List<?> qyList = super.query(sql);
		return (List<Quyu>) qyList;
	}

	public String addNewQy(Quyu qy) {
		String sql = "INSERT INTO qy(QYCODE,QYNAME) VALUES('" + qy.getQyCode() + "','" + qy.getQyName() + "')";
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return "";
	}

	public String removeQy(String qyCode) {
		String sql = "DELETE FROM qy WHERE qyCode = '" + qyCode + "'";
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return "";
	}

	public Quyu getQuyuByCode(String code) {
		String sql = "SELECT * FROM qy WHERE qyCode = '" + code + "'";
		List<?> quyuList = super.query(sql);
		if (quyuList == null || quyuList.isEmpty()) {
			return null;
		}
		return (Quyu) quyuList.get(0);
	}
}
